package com.gcxx.framework.security.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;

import com.gcxx.framework.base.dao.BaseDAO;
import com.gcxx.framework.security.dao.IFrsfOrgDAO;
import com.gcxx.framework.security.entity.FrsfOrg;
import com.gcxx.framework.security.entity.FrsfUser;
import com.gcxx.framework.security.entity.ViewFrsfOrg;
import com.gcxx.framework.tools.Constants;
import com.gcxx.framework.util.properties.InitPropertiesUtil;
import com.gcxx.framework.util.string.StringUtil;

/**
 * A data access object (DAO) providing persistence and search support for
 * FrsfOrg entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.gcxx.framework.security.dao.FrsfOrg
 * @author MyEclipse Persistence Tools
 */

public class FrsfOrgDAO extends BaseDAO implements IFrsfOrgDAO{
	private static final Log log = LogFactory.getLog(FrsfOrgDAO.class);

	protected void initDao() {
		// do nothing
	}

	public void save(FrsfOrg transientInstance) {
		log.debug("saving FrsfOrg instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(FrsfOrg persistentInstance) {
		log.debug("deleting FrsfOrg instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public FrsfOrg findById(java.lang.String id) {
		log.debug("getting FrsfOrg instance with id: " + id);
		try {
			Map map = new HashMap();
			map.put("id", id);
			String bean = FrsfOrg.class.getName();
			if(Constants.ORGUSER_FROM_OUT.equals(InitPropertiesUtil.getProperty("orguser.from"))){
				bean = ViewFrsfOrg.class.getName();
			}
			String Hql= "from " + bean + " where  id= :id";
		  
			List result = findByHQLMap(Hql, map);
			if(result != null && !result.isEmpty()){
				FrsfOrg instance =(FrsfOrg)result.get(0);
				return instance;
			}
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
		return null;
	}

	public List findByExample(FrsfOrg instance) {
		log.debug("finding FrsfOrg instance by example");
		try {
//			Obejct obj = 
			if(Constants.ORGUSER_FROM_OUT.equals(InitPropertiesUtil.getProperty("orguser.from"))){
				instance = (ViewFrsfOrg)instance;
			}
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding FrsfOrg instance with property: " + propertyName
				+ ", value: " + value);
		try {
			
			String bean = FrsfOrg.class.getName();
			if(Constants.ORGUSER_FROM_OUT.equals(InitPropertiesUtil.getProperty("orguser.from"))){
				bean = ViewFrsfOrg.class.getName();
			}
			
			String queryString = "from " + bean + " as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findAll() {
		log.debug("finding all FrsfOrg instances");
		try {
			/** begin update by guoyi 20130913 for ftp绩效考核 **/
			//String queryString = "from FrsfOrg where orgState='1'";
			String bean = FrsfOrg.class.getName();
			String queryString = "from ";
			if(Constants.ORGUSER_FROM_OUT.equals(InitPropertiesUtil.getProperty("orguser.from"))){
				bean = ViewFrsfOrg.class.getName();
				queryString += bean;
			}else{
				queryString += bean + " where orgState='1'";
			}
			queryString += " order by orgLevelId, displayOrder";
			/** end update by guoyi 20130913 for ftp绩效考核 **/
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public FrsfOrg merge(FrsfOrg detachedInstance) {
		log.debug("merging FrsfOrg instance");
		try {
			FrsfOrg result = (FrsfOrg) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(FrsfOrg instance) {
		log.debug("attaching dirty FrsfOrg instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			
//			Map map = new HashMap();
//			map.put("id", instance.getId());
//			map.put("orgName", instance.getOrgName());
//			map.put("orgLevelId",instance.getOrgLevelId());
//			
//			String sql = "update " + FrsfOrg.class.getName() + " set orgName= :orgName, orgLevelId= :orgLevelId where id= :id ";
//			execute(sql, map);
			
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(FrsfOrg instance) {
		log.debug("attaching clean FrsfOrg instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public void deleteOrgById(String id){
		Map map = new HashMap();
		map.put("id", id);
		map.put("orgState", "0");

		String sql = "update " + FrsfOrg.class.getName() + " set orgState= :orgState where id= :id ";
		execute(sql, map);
	}

	public static FrsfOrgDAO getFromApplicationContext(ApplicationContext ctx) {
		return (FrsfOrgDAO) ctx.getBean("FrsfOrgDAO");
	}
	
	/* 
	 * (non-Javadoc)
	 * @see com.gcxx.framework.security.dao.IFrsfOrgDAO#findOrgUserList(java.util.Map, java.lang.String[], int, int)
	 */
	public Map findOrgUserList( Map condition, String[] order,int index,int pageSize,String flag) {
		StringBuffer hql = new StringBuffer();
		hql.append("select count(*) from " + FrsfUser.class.getName() + " where 1=1 ");
		Map map = new HashMap();
		Map resultMap=new HashMap();
		if(condition != null && !condition.isEmpty()){
			if(condition.get("orgId") != null){
				map.put("orgId", condition.get("orgId") );
				if("1".equals(flag)){
					hql.append("and (orgID != :orgId or orgID is null)");
				}else{					
					hql.append("and orgID = :orgId ");
				}
			}
			if(condition.get("empName") != null){
				map.put("empName", "%" + condition.get("empName") + "%");
				hql.append("and empName like :empName ");
			}
			if(condition.get("account") != null){
				map.put("account", "%" + condition.get("account") + "%");
				hql.append("and account like :account ");
			}
			hql.append("and state = 1 ");
		}
		
		/*if(order != null && order.length > 0){
			hql.append("order by ");
			for (int i = 0; i < order.length; i++) {
				hql.append(" " +order[i]);
				if(i < order.length - 1){
					hql.append(",");
				}
			}
		}*/

		List result = null;
		int totalSize=0;
		String queryHql = hql.substring(16);
		int pageNo=(index/pageSize)+1;
		result=this.findPageByQuery(pageNo,pageSize,queryHql, map);
		totalSize=this.getTotalCount(hql.toString(), map);

		resultMap.put("result", result);
		resultMap.put("totalSize", totalSize);
		return resultMap;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.gcxx.framework.security.dao.IFrsfOrgDAO#deleteOrgUsers(java.lang.String, java.lang.String[])
	 */
	public void deleteOrgUsers(String orgId, String [] ids){
		Map map = new HashMap();
		for (int i = 0; i < ids.length; i++) {
			String id = ids[i];
			map.put("orgId", orgId);
			map.put("id", id);
			String sql = "update " + FrsfUser.class.getName() + " set orgID='' where id= :id and orgID=:orgId ";
			execute(sql, map);
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.gcxx.framework.security.dao.IFrsfOrgDAO#addOrgUsers(java.lang.String, java.lang.String[])
	 */
	public void addOrgUsers(String orgId,String [] ids){
		Map map = new HashMap();
		for (int i = 0; i < ids.length; i++) {
			String id = ids[i];
			map.put("orgId", orgId);
			map.put("id", id);
			String sql = "update " + FrsfUser.class.getName() + " set orgID = :orgId where id= :id ";
			execute(sql, map);
		}
		
	}
	
	/* (non-Javadoc)
	 * @see com.gcxx.framework.security.dao.IFrsfOrgDAO#findListByCondition(java.util.Map, java.util.Map, java.lang.String[])
	 */
	public List<FrsfOrg> findListByCondition(Map condition, Map conditionMark, String[] order){
		StringBuffer sql = new StringBuffer();
		
		String bean = FrsfOrg.class.getName();
		if(Constants.ORGUSER_FROM_OUT.equals(InitPropertiesUtil.getProperty("orguser.from"))){
			bean = ViewFrsfOrg.class.getName();
		}
		
		sql.append("select id, org_name, org_short_name, org_level_id, org_no, upper_org_id, is_business from " + bean +" t where 1=1 ");
		if(condition != null && !condition.isEmpty()){
			if(condition.get("orgId") != null){
				sql.append("and id = :orgId ");
			}
			if(condition.get("orgName") != null){
				condition.put("orgName","%" + condition.get("orgName") + "%");
				sql.append("and org_name ");
				if(conditionMark != null && !conditionMark.isEmpty() && StringUtil.isNotNull((String)conditionMark.get("orgName"))){
					sql.append(conditionMark.get("orgName"));
				}else{
					sql.append(" like ");
				}
				sql.append(" :orgName ");
			}
			if(condition.get("orgLevelId") != null){
				sql.append("and org_level_id = :orgLevelId ");
			}
		}
		if(order != null && order.length > 0){
			sql.append("order by ");
			for (int i = 0; i < order.length; i++) {
				sql.append(" " +order[i]);
				if(i < order.length - 1){
					sql.append(",");
				}
			}
		}
		return findBySQLBean(sql.toString(), FrsfOrg.class, condition);
	}

	@Override
	public boolean checkOrgNoExsit(String orgNo) {
		
		if(StringUtil.isNotNullAndSNull(orgNo)){
			StringBuffer sql = new StringBuffer();
			String bean = FrsfOrg.class.getName();
			
			if(Constants.ORGUSER_FROM_OUT.equals(InitPropertiesUtil.getProperty("orguser.from"))){
				bean = ViewFrsfOrg.class.getName();
			}
			
			sql.append("select id from " + bean +" t where 1=1 and orgNo = :orgNo");
			Map condition = new HashMap();
			condition.put("orgNo", orgNo);
			
			List orgList = findByHQLMap(sql.toString(), condition);
			//如果机构集合不为空则返回ture
			if(orgList != null && !orgList.isEmpty()){
				return true;
			}
		}
		
		return false;
	}
	
}